package bdsender

import (
	"errors"
	"strconv"
	"strings"
)

func bytify(bs string) ([]byte, error) {
	bits := len(bs)
	if bits%8 != 0 {
		rem := make([]byte, 8-bits%8)
		for idx := range rem {
			rem[idx] = '0'
		}
		rems := string(rem)
		bs = bs + rems
		bits = len(bs)
	}
	var num = bits / 8
	bytes := make([]byte, num)
	for i := 0; i < num; i++ {
		b := bs[i*8 : (i+1)*8]
		v, err := strconv.ParseUint(b, 2, 8)
		if err != nil {
			return nil, err
		}
		bytes[i] = byte(v)
	}
	return bytes, nil
}

// Slot slot definition
type Slot struct {
	Head  []byte `json:"head,omitempty"`
	Items []item `json:"items,omitempty"`
}

// NewSlot create new slot
func NewSlot(head []byte, items []item) (*Slot, error) {
	return &Slot{head, items}, nil
}

// Encode a slot
func (s *Slot) Encode(data string) ([]byte, error) {
	bs := ""
	for _, it := range s.Items {
		b, err := it.Encode(data)
		if err != nil {
			return []byte{}, err
		}
		if strings.Contains(b, "-") {
			// s.log.Error("encode error contains invalid char")
			return []byte{}, errors.New("encode error contains invalid char")
		}
		bs = bs + b
	}
	b, err := bytify(bs)
	if err != nil {
		return []byte{}, err
	}
	return append(s.Head, b...), nil
}

// Decode a slot
func (s *Slot) Decode(bytes []byte) ([]byte, error) {
	return nil, nil
}
